package com.hhl.api.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class OrderController {
	/**
	 * RestTemplate 是SpringBoot Web组件提供 默认整合ribbon负载均衡器 reset方式底层是采用httpclient技术
	 */
	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private DiscoveryClient discoveryClient;
	 
	@RequestMapping("/getorder")
	public String getOrder() {
		// 有两种方式 一种是采用服务别名方式调用，另一种是直接调用(不会走注册中心)
		// order 使用rpc 远程调用技术 调用 会员服务
		String memberUrl = getServiceUrl("consul-member") + "/getMember";
		String result = restTemplate.getForObject(memberUrl, String.class);
		System.out.println("会员服务调用订单服务,result:" + result);
		return result;
	}

	@RequestMapping("/getServiceUrl")
	public List<String> getServiceUrl() {
		List<ServiceInstance> list = discoveryClient.getInstances("consul-member");
		List<String> services = new ArrayList<>();
		for (ServiceInstance serviceInstance : list) {
			if (serviceInstance != null) {
				services.add(serviceInstance.getUri().toString());
			}
		}
		return services;
	}
	
	public String getServiceUrl(String name) {
		List<ServiceInstance> list = discoveryClient.getInstances(name);
		if (list != null && !list.isEmpty()) {
			return list.get(0).getUri().toString();
		}
		return null;
	}
}
